package com.sikaryofficial.canalclient.handler;

import com.sikaryofficial.canalclient.domain.doc.ActivityDoc;
import com.sikaryofficial.canalclient.domain.jpa.ActivityPO;
import com.sikaryofficial.canalclient.domain.mapping.ActivityMapping;
import com.sikaryofficial.canalclient.eemapper.ActivityEeMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * @author : qinjinyuan
 * @desc :
 * @date : 2023/12/25 15:33
 */

@CanalTable("activity_t")
@Component
@AllArgsConstructor
@Slf4j
public class ActivityHandler implements EntryHandler<ActivityPO> {

    @Autowired
    private ActivityEeMapper activityMapper;

    @Override
    public void insert(ActivityPO activity) {
        log.info("insert Activity{}", activity);
        ActivityDoc activity1 = ActivityMapping.INSTANCE.coverReqToEntity(activity);
        activityMapper.insert(activity1);
    }

    @Override
    public void update(ActivityPO before, ActivityPO after) {
        log.info("update Activity{} -> {}", before, after);

        ActivityDoc activity = ActivityMapping.INSTANCE.coverReqToEntity(after);

        long count = activityMapper.selectCount(new LambdaEsQueryWrapper<ActivityDoc>()
                .eq(ActivityDoc::getActivityId, activity.getActivityId())
              );
        if(count == 0){
            activityMapper.insert(activity);
        }else {
            activityMapper.updateById(activity);
        }
    }

    @Override
    public void delete(ActivityPO activity) {
        log.info("delete Activity{}", activity);
        ActivityDoc activity1 = ActivityMapping.INSTANCE.coverReqToEntity(activity);
        activityMapper.deleteById(activity1.getActivityId());
    }
}
